package com.csot.ipscan;

import cn.hutool.core.thread.lock.LockUtil;
import com.alibaba.druid.util.StringUtils;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class DequeTask implements Runnable {

    Log log = Log.getLog(DequeTask.class);

    private static ReentrantReadWriteLock lock = LockUtil.createReadWriteLock(true);

    @Override
    public void run() {

        log.info("开始定时任务");

        if (lock.isWriteLocked()) {
            return;
        }
        for (int i = 0; i < 10; i++) {
            String data = "";
            try {
                boolean b = lock.writeLock().tryLock(5, TimeUnit.SECONDS);
                if (!b) {
                    return;
                }
                data = SysData.postdeque.poll();
                if (StringUtils.isEmpty(data)) {
                    return;
                }
                HttpKit.post(PropKit.get("url"), data);

            } catch (Exception e) {
                log.error("定时队列处理错误", e);
                SysData.postdeque.add(data);
            } finally {
                lock.writeLock().unlock();
                i++;
            }
        }

    }
}
